package br.com.tecnoria.controllers
{
	import br.com.tecnoria.vo.OrderVO;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.swizframework.utils.services.ServiceHelper;

	public class OrderController
	{
		[Inject("orderRemote")]
		public var remote:RemoteObject;
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Bindable]
		public var dataProvider:ArrayCollection;
		
		[Bindable]
		public var order:OrderVO;
		
		
		
		/**
		 * Call Function
		 */
		
		[EventHandler(event="OrderEvent.SAVE", properties="order")]
		public function saveOrder(order:OrderVO):void
		{
			serviceHelper.executeServiceCall(remote.saveOrder(order), onSaveOrder, onFault);
		}
		
		[EventHandler(event="OrderEvent.LIST")]
		public function listOrder():void
		{
			serviceHelper.executeServiceCall(remote.listOrder(), onListOrder, onFault);
		}
		
		[EventHandler(event="OrderEvent.UPDATE", properties="order")]
		public function updateOrder(order:OrderVO):void
		{
			serviceHelper.executeServiceCall(remote.updateOrder(order), onUpdateOrder, onFault);
		}
		
		[EventHandler(event="OrderEvent.DELETE", properties="order")]
		public function deleteOrder(order:OrderVO):void
		{
			serviceHelper.executeServiceCall(remote.deleteOrder(order), onDeleteOrder, onFault);
		}
		
		[EventHandler(event="OrderEvent.SEARCH", properties="order")]
		public function searchOrder(order:OrderVO):void
		{
			serviceHelper.executeServiceCall(remote.searchOrder(order.idOrder), onListOrder, onFault);
		}
		
		/**
		 * Result Function
		 */
		
		public function onSaveOrder(result:ResultEvent):void
		{
			Alert.show("Pedido salvo com sucesso!");
			order = new OrderVO(result.result);
		}
		
		public function onListOrder(result:ResultEvent):void
		{
			dataProvider = new ArrayCollection(result.result as Array);
		}
		
		public function onUpdateOrder(result:ResultEvent):void
		{
			Alert.show("Pedido alterado com Sucesso!");
			order = new OrderVO(result.result);
		}
		public function onDeleteOrder(result:ResultEvent):void
		{
			Alert.show("Pedido removido com Sucesso!");
			listOrder();
		}
		
		/**
		 * Fault Function
		 */
		
		public function onFault(result:FaultEvent):void
		{
			Alert.show(result.fault.toString(), "Erro");
		}
	}
}